#!/bin/sh

# Global variables
DEBIANPATH="/data/local/tmp/chrootDebian"
DOWNLOAD_URL="https://github.com/LinuxDroidMaster/Termux-Desktops/releases/download/Debian/debian12-arm64.tar.gz"
START_SCRIPT_URL="https://gitee.com/samisold/repo/raw/master/termux-chroot-debian/start_debian.sh"
STARTXFCESCRIPT_URL="https://gitee.com/samisold/repo/raw/master/termux-chroot-debian/startxfce4_chrootDebian.sh"

# Function to show farewell message
goodbye() {
    echo -e "\e[1;31m[!] Something went wrong. Exiting...\e[0m"
    exit 1
}

# Function to show progress message
progress() {
    echo -e "\e[1;36m[+] $1\e[0m"
}

# Function to show success message
success() {
    echo -e "\e[1;32m[✓] $1\e[0m"
}

# Function to show warning message
warning() {
    echo -e "\e[1;33m[!] $1\e[0m"
}

# Function to download file with conditional check
download_file() {
    local target_dir="$1"
    local file_name="$2"
    local url="$3"
    
    if [ -f "${target_dir}/${file_name}" ]; then
        warning "File already exists: ${file_name}"
        warning "Skipping download..."
        return 0
    fi

    progress "Downloading ${file_name}..."
    busybox wget -O "${target_dir}/${file_name}" "$url"
    
    if [ $? -eq 0 ]; then
        success "Download completed: ${file_name}"
    else
        echo -e "\e[1;31m[!] Download failed: ${file_name}\e[0m"
        goodbye
    fi
}

# Function to handle archive extraction
extract_file() {
    local target_dir="$1"
    local archive_name="debian12-arm64.tar.gz"

    if [ -d "${target_dir}/debian12-arm64" ]; then
        warning "Directory exists: debian12-arm64"
        warning "Skipping extraction..."
        return 0
    fi

    progress "Extracting ${archive_name}..."
    tar xpvf "${target_dir}/${archive_name}" -C "$target_dir" --numeric-owner >/dev/null 2>&1
    
    if [ $? -eq 0 ]; then
        success "Extraction completed"
    else
        echo -e "\e[1;31m[!] Extraction failed\e[0m"
        goodbye
    fi
}

# Function to handle script deployment
deploy_script() {
    local script_path="/data/local/tmp/start_debian.sh"

    if [ -f "$script_path" ]; then
        warning "Script exists: start_debian.sh"
        warning "Skipping deployment..."
        return 0
    fi

    progress "Deploying chroot management script..."
    busybox wget -O "$script_path" "$START_SCRIPT_URL"
    
    if [ $? -eq 0 ]; then
        chmod +x "$script_path"
        success "Script deployed successfully"
    else
        echo -e "\e[1;31m[!] Script deployment failed\e[0m"
        goodbye
    fi
}

# Function to configure chroot mounts
configure_mounts() {
    progress "Configuring filesystem mounts..."
    
    busybox mount -o remount,dev,suid /data
    busybox mount --bind /dev $DEBIANPATH/dev
    busybox mount --bind /sys $DEBIANPATH/sys
    busybox mount --bind /proc $DEBIANPATH/proc
    busybox mount -t devpts devpts $DEBIANPATH/dev/pts

    mkdir -p $DEBIANPATH/dev/shm
    busybox mount -t tmpfs -o size=256M tmpfs $DEBIANPATH/dev/shm

    mkdir -p $DEBIANPATH/sdcard
    busybox mount --bind /sdcard $DEBIANPATH/sdcard
}

# Function to execute in chroot environment
chroot_exec() {
    local command="$@"
    busybox chroot $DEBIANPATH /bin/sh -c "$command"
}

# Function to configure base environment
configure_environment() {
    progress "Configuring base system..."
    
    chroot_exec "apt update -y && 
    apt upgrade -y && 
    echo 'nameserver 8.8.8.8' > /etc/resolv.conf && 
    echo '127.0.0.1 localhost' > /etc/hosts && 
    groupadd -g 3003 aid_inet && 
    groupadd -g 3004 aid_net_raw && 
    groupadd -g 1003 aid_graphics && 
    usermod -g 3003 -G 3003,3004 -a _apt && 
    usermod -G 3003 -a root && 
    apt install -y nano vim net-tools sudo git"
}

# Function to create user account
create_user() {
    progress "Creating user account..."
    
    while true; do
        echo -n "Enter username: "
        read username
        [ -n "$username" ] && break
        warning "Username cannot be empty"
    done

    chroot_exec "adduser --gecos '' $username"
    chroot_exec "usermod -aG aid_inet $username"
    chroot_exec "echo '$username ALL=(ALL:ALL) ALL' >> /etc/sudoers"
}

# Function to install desktop environment
install_desktop() {
    PS3="Select desktop environment: "
    options=("XFCE4" "KDE Plasma" "Cinnamon" "LXDE")
    
    select opt in "${options[@]}"; do
        case $REPLY in
            1) 
                progress "Installing XFCE4..."
                chroot_exec "apt install -y dbus-x11 xfce4 xfce4-terminal"
                deploy_xfce_script
                break
                ;;
            2) 
                warning "KDE installation not yet implemented"
                break
                ;;
            3) 
                warning "Cinnamon installation not yet implemented"
                break
                ;;
            4) 
                warning "LXDE installation not yet implemented"
                break
                ;;
            *) 
                warning "Invalid selection"
                ;;
        esac
    done
}

# Function to deploy XFCE startup script
deploy_xfce_script() {
    local script_path="./startxfce4_chrootDebian.sh"
    
    progress "Deploying XFCE startup script..."
    busybox wget -O "$script_path" "$STARTXFCESCRIPT_URL"
    
    if [ $? -eq 0 ]; then
        chmod +x "$script_path"
        success "XFCE script deployed"
    else
        warning "Failed to deploy XFCE script"
    fi
}

# Main execution flow
main() {
    [ "$(whoami)" != "root" ] && {
        echo -e "\e[1;31m[!] Requires root privileges\e[0m"
        goodbye
    }

    # Create working directory
    mkdir -p "$DEBIANPATH" || goodbye

    # File handling
    download_file "$DEBIANPATH" "debian12-arm64.tar.gz" "$DOWNLOAD_URL"
    extract_file "$DEBIANPATH"
    deploy_script

    # System configuration
    configure_mounts
    configure_environment
    create_user
    install_desktop

    # Final configuration
    sed -i "s/droidmaster/$username/g" "/data/local/tmp/start_debian.sh"
    success "Configuration complete. Start with: ./start_debian.sh"
}

# ASCII art display
echo -e "\e[32m"
cat << "EOF"
___  ____ ____ _ ___  _  _ ____ ____ ___ ____ ____    ____ _  _ ____ ____ ____ ___ 
|  \ |__/ |  | | |  \ |\/| |__| [__   |  |___ |__/    |    |__| |__/ |  | |  |  |  
|__/ |  \ |__| | |__/ |  | |  | ___]  |  |___ |  \    |___ |  | |  \ |__| |__|  |  
                                                                                   
EOF
echo -e "\e[0m"

# Start main process
main